import axios, { AxiosRequestConfig } from "axios";
import Url from "url-parse";
import * as store from "store";
import { S_MAN_APP, S_MAN_TOKEN } from "../utils/constant";

export const isProd = process.env.NODE_ENV === "production";

// "http://47.112.180.188:3030"
// "http://pase-repo-uat.pingan.com.cn:8081";

export const host = isProd
  ? "http://localhost:3030/"
  : "http://localhost:3030/"

export const instance = axios.create({
  timeout: 300 * 1000
});

export const Message = (opt: object) => {
  console.log(opt)
}

class AuthError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "authError";
  }
}

instance.interceptors.request.use(
  function(config) {
    config.headers["token"] = store.get(S_MAN_TOKEN) || "";
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    const res = response.data;
    if (+res.errCode === 0) {
      res.success = true;
    } else {
      res.success = false;
      Message({
        type: "error",
        message: res.errMsg
      });
    }
    return res;
  },
  error => {
    if (error.message.indexOf("401") !== -1) {
      window.location.href = "/account/login"
      return Promise.reject(new AuthError("未登录"));
    } else {
      Message({
        type: "error",
        message: error
      });
      return Promise.reject(error);
    }
  }
);

interface AppRequestConfig extends AxiosRequestConfig {
  query?: object;
}

export const request = function(option: AppRequestConfig) {
  option.url = host + option.url;

  // 最小 loading 时间
  const p1 = new Promise(resolve => {
    setTimeout(() => resolve(1), 200);
  })

  // 不设置超时时常
  if (option.timeout === 0) {
    option.timeout = 1000 * 3600 * 24;
  }

  {
    // 添加统一参数
    const url = new Url(option.url, true);
    const query: any = {};
    Object.keys(url.query).forEach(key => {
      if (url.query[key] !== "") {
        query[key] = url.query[key];
      }
    });

    // 可能会直接传入
    if (
      !url.query.app_key ||
      (option.query && !(option.query as any).app_key) ||
      (option.data && !(option.data as any).app_key)
    ) {
      const app_key = store.get(S_MAN_APP) || "";
      if (app_key) {
        query.app_key = app_key;
      }
    }

    Object.assign(url.query, query, option.query);
    option.url = url.toString();
  }

  const p2 = instance(option);

  return Promise.allSettled([p1, p2]).then((res: any) => {
    const { reason, value } = res[1];
    if (!reason) return value;
  })
};
